import  cv2 as cv
import numpy as np

filename = r'lena.jpg'
img = cv.imread(filename)
cv.imshow('original img',img)

# cv.CV_64F将像素值转换为double型，不然计算后为负值的像素会被截断为0
sobelx= cv.Sobel(img,cv.CV_64F,1,0)
#转换为uint8类型（x方向）
sobelx = cv.convertScaleAbs(sobelx)
cv.imshow('sobelx',sobelx)
cv.imwrite('sobelx.jpg',sobelx)

sobely = cv.Sobel(img,cv.CV_64F,0,1)
sobely = cv.convertScaleAbs(sobely)
cv.imshow('sobely',sobely)
cv.imwrite('sobely.jpg',sobely)

#直接x，y方向一起计算（效果不好，应分开计算，再求权重和）
sobelxy = cv.Sobel(img,cv.CV_64F,1,1)
sobelxy = cv.convertScaleAbs(sobelxy)
cv.imshow('sobelxy',sobelxy)
cv.imwrite('sobelxy.jpg',sobelxy)

#图像权重和
# src1 图一  alpha->图一的权重  src2->图二 beta->图二的权重 gamma->修正值
# dst = src1*alpha+src2*beta+gamma
sobel = cv.addWeighted(sobelx,0.5,sobely,0.5,0)
cv.imshow('sobel',sobel)
cv.imwrite('sobel.jpg',sobel)
cv.waitKey()

canny1 = cv.Canny(img,50,100)
canny2 = cv.Canny(img,100,200)
cv.imshow("canny1",canny1)
cv.imshow("canny2",canny2)
cv.waitKey()

cv.destroyAllWindows()
